package com.zy.explore.vo;

import com.zy.explore.frm.OffsetFrm;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.val;
import org.springframework.data.domain.Page;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * description 标准 offset 响应实体
 *
 * @author ZY
 * @date 2021-05-05 18:14
 * @see OffsetFrm offset 请求实体
 */
@Getter
@Setter
@ApiModel
@Builder(builderClassName = "Builder")
@NoArgsConstructor
@AllArgsConstructor
public class OffsetVO<T> {

    /**
     * 页序数
     */
    @ApiModelProperty(value = "offset 号", dataType = "long")
    private long offset;

    /**
     * 当页记录数量
     */
    @ApiModelProperty(value = "当页记录数量", dataType = "int")
    private int size;

    /**
     * 记录总数
     */
    @ApiModelProperty(value = "记录总数", dataType = "int")
    private long total;

    /**
     * 元素列表
     */
    @ApiModelProperty(value = "当前页元素", dataType = "int")
    private List<T> rows;

    /**
     * 下一页页码
     */
    @ApiModelProperty(value = "下一页页码，没有下一页返回 -1", dataType = "int")
    private long nextOffset;

    public OffsetVO(Page<T> page) {
        val pageable = page.getPageable();

        this.offset = pageable.getOffset();
        this.size = page.getSize();
        this.total = page.getTotalElements();
        this.rows = page.getContent();
        this.nextOffset = offset + pageable.getPageSize() < total ? offset + pageable.getPageSize() : -1L;
    }

    public <R> OffsetVO<R> mapRows(Function<? super T, ? extends R> converter) {
        return OffsetVO.<R>builder()
            .offset(this.offset)
            .size(this.size)
            .total(this.total)
            .nextOffset(this.nextOffset)
            .rows(this.rows.stream().map(converter).collect(Collectors.toList()))
            .build();
    }
}
